package com.running.crm.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.Element;
import org.springframework.web.servlet.ModelAndView;

import com.cmcc.mm7.vasp.common.MMConstants;
import com.cmcc.mm7.vasp.common.MMContentType;
import com.isomorphic.datasource.DataSource;
import com.isomorphic.datasource.DataSourceManager;
import com.running.crm.CrmConstants;
import com.running.mms.smil.SmilFileReader;
import com.running.mms.smil.SmilFileWriter;
import com.running.util.DateUtils;
import com.running.util.FileOperator;
import com.running.util.StringUtils;
@SuppressWarnings("unchecked")
public class MmsConfigController extends AbstractController {
	static DataSource mmsDao;
	static DataSource mmsContentDao;
	
	static{
		//获得datasource
		try {
			mmsDao = DataSourceManager.getDataSource("mms");
			mmsContentDao = DataSourceManager.getDataSource("mms_content");
		} catch (Exception e) {
				e.printStackTrace();
		}
	}
	public ModelAndView append(HttpServletRequest request,
			HttpServletResponse response) {
		return new ModelAndView(this.viewPage);
	}
	public ModelAndView sendAppend(HttpServletRequest request,
			HttpServletResponse response) {
		return new ModelAndView("crm/core/mms/appendMms");
	}

	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) {
		String queryString = "FROM Mms WHERE 1=1 ";
		return new ModelAndView(this.viewPage);
	}
	
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String mmsSid = StringUtils.varFormat(request.getParameter("mmsSid"));
		Map mms = mmsDao.fetchById(mmsSid);
		if (mms == null) {
			request.setAttribute("message", this.MSG_NO_DATA_FOUND);
			return new ModelAndView(this.failView);
		}

		
		mmsDao.remove(mms);
		request.setAttribute("redirectUrl", this.requestUri+".do?method=list");
		request.setAttribute("message", this.MSG_SUCCESS);
		return new ModelAndView(this.successView);
	}
	
	public ModelAndView edit(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String mmsSid = StringUtils.varFormat(request.getParameter("mmsSid"));
		Map mms = mmsDao.fetchById(mmsSid);
		if (mms == null) {
			request.setAttribute("message", this.MSG_NO_DATA_FOUND);
			return new ModelAndView(this.failView);
		}

		request.setAttribute("mms", mms);
		Map smilContent = null;
		List<Map> mmsContents = mmsContentDao.fetch("mms_sid_fk", mmsSid);
		request.setAttribute("mmsContents", mmsContents);
		for(Map content:mmsContents){
			if(MMConstants.ContentType.SMIL.match((String)content.get("content_type"))){
				smilContent = content;
				break;
			}
		}
		if (smilContent == null) {
			request.setAttribute("message", "无效的彩信配置--没有smil文件");
			return new ModelAndView(this.failView);
		}
		String rootDir = request.getSession().getServletContext().getRealPath("/").replaceAll("\\\\","/");	//根目录
    	if (rootDir.endsWith("/")) {
    		rootDir = rootDir.substring(0,rootDir.length()-1);
    	}    		
    	if (FileOperator.exists(rootDir + "/" + smilContent.get("file_dir") + "/" + smilContent.get("file_name"))) {
			SmilFileReader reader = new SmilFileReader(rootDir + "/" + smilContent.get("file_dir") + "/" + smilContent.get("file_name"));
			request.setAttribute("smilContents", reader.getPars());
			return new ModelAndView(this.viewPage);
		} else {
			request.setAttribute("message", "无效的彩信配置--没有smil文件");
			return new ModelAndView(this.failView);
		}
	}
	public ModelAndView show(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
			return this.edit(request, response);
		}	
	//修改的业务逻辑是：将原来的Mms对象删除,MmsContent不作任何改动,再新增Mms对象和MmsContent对象
	public ModelAndView saveEdit(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String mmsSid = StringUtils.varFormat(request.getParameter("mmsSid"));
		Map mms = mmsDao.fetchById(mmsSid);
		if (mms == null) {
			request.setAttribute("message", this.MSG_NO_DATA_FOUND);
			return new ModelAndView(this.failView);
		}

		mmsDao.delete(mms);
		return saveMms(request,response);
	}

	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
//		saveMMSendConfig(request);
		
		return saveMms(request,response);
	}
    @SuppressWarnings("rawtypes")
	private ModelAndView saveMms(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	Map currUser = (Map) request.getSession().getAttribute("currUser");
    	String company = request.getParameter("company");
    	if(currUser == null){
    		response.sendRedirect("login.jsp");
    	}
    	String corp_sid_fk = (String) currUser.get("corp_sid");
    	Integer user_sid_fk = (Integer) currUser.get("pk");
    	Set<Map> contents = new HashSet<Map>();
    	String incomingCallState = StringUtils.varFormat(request.getParameter("incomingCallState"));
    	String outcomingCallState = StringUtils.varFormat(request.getParameter("outcomingCallState"));
    	if ((!"Y".equals(outcomingCallState))||"".equals(outcomingCallState)) {
    		outcomingCallState = "N";
    	}
    	if ((!"Y".equals(incomingCallState))||"".equals(incomingCallState)) {
    		incomingCallState = "N";
    	}
    	SmilFileWriter smil = new SmilFileWriter();
    	//文件路径
    	String rootDir = request.getSession().getServletContext().getRealPath("/").replaceAll("\\\\","/");	//根目录
    	if (rootDir.endsWith("/")) {
    		rootDir = rootDir.substring(0,rootDir.length()-1);
    	}
    	String baseDir = CrmConstants.MMS_BASE_DIR;
    	
    	int frameCount = 0;
    	try {
    		frameCount = Integer.parseInt(request.getParameter("frameCount"));
    	} catch (Exception ex) {
    		frameCount = 0;
    	}
    	if (frameCount == 0) {
    		request.setAttribute("message", "彩信必须有内容");
    		request.setAttribute("redirectUrl", this.requestUri+"?method=append");
    		return new ModelAndView(this.failView);
    	}
    	
    	String subject = StringUtils.varFormat(request.getParameter("subject"));
    	smil.setTitle(subject);
    	String file = DateUtils.getDate("yyMMddHHmmssSSSS");
    	//生成彩信每帧的数据
		for(int i=1;i<=frameCount;i++){
			
			String frameTime = StringUtils.varFormat(request.getParameter("frameTime"+String.valueOf(i)));
			Element par = smil.newPar(frameTime+"000");
			//处理图片,生成相应的MmsContent
			String imgFileDir = StringUtils.varFormat(request.getParameter("imgFileDir"+String.valueOf(i)));
			String imgFileName = StringUtils.varFormat(request.getParameter("imgFileName"+String.valueOf(i)));
			if(!"".equals(imgFileName)){
				if (FileOperator.exists(rootDir +"/"+ imgFileDir + "/" + imgFileName)) {
					//生成一个MmsContent
					Map content = new HashMap();
					content.put("charset",CrmConstants.Charset.UTF8);
					content.put("content_id",imgFileName);
					content.put("content_location",imgFileName);
					long size = FileOperator.size(rootDir + "/" + imgFileDir + "/" + imgFileName);
					if (size > 0) {
						try {
							content.put("file_size",((int)size/1024) + 1);
						} catch (Exception ex) {
							content.put("file_size",0);
						}
					} else {
						content.put("file_size",0);
					}
					content.put("file_dir",imgFileDir);
					content.put("file_name",imgFileName);
					content.put("content_type",this.getMmsContentType(imgFileName));
					//将MmsContent放进HashSet
					contents.add(content);
					par.addContent(smil.newImg(imgFileName));
					
				}
			}
			
			
			String mmsText = StringUtils.varFormat(request.getParameter("mmsText"+String.valueOf(i)));
			Integer fileSize = 0;
			//文件名基名
			//处理文本
			if(!"".equals(mmsText)){
				String fileName = file + "_" + i + ".txt";
				if (FileOperator.write(rootDir + "/" + baseDir, fileName, mmsText)) {//文件写入成功
					//生成一个MmsContent
					
					Map content = new HashMap();
					content.put("charset",CrmConstants.Charset.UTF8);
					content.put("content_id",fileName);
					content.put("content_location",fileName);
					long size = FileOperator.size(rootDir + "/" + baseDir + "/" + fileName);
					if (size > 0) {
						try {
							content.put("file_size",((int)size/1024) + 1);
						} catch (Exception ex) {
							content.put("file_size",0);
						}
					} else {
						content.put("file_size",0);
					}
					content.put("file_dir",baseDir);
					content.put("file_name",fileName);
					content.put("content_type",this.getMmsContentType(fileName));
					//将MmsContent放进HashSet
					contents.add(content);
					par.addContent(smil.newText(fileName));
				}
			}
			
			//处理音频,生成相应的MmsContent
			String voiFileDir = StringUtils.varFormat(request.getParameter("voiFileDir"+String.valueOf(i)));
			String voiFileName = StringUtils.varFormat(request.getParameter("voiFileName"+String.valueOf(i)));
			if(!"".equals(voiFileName)){
				if (FileOperator.exists(rootDir +"/"+ voiFileDir + "/" + voiFileName)) {
					//生成一个MmsContent
					Map content = new HashMap();
					content.put("charset",CrmConstants.Charset.UTF8);
					content.put("content_id",voiFileName);
					content.put("content_location",voiFileName);
					
					long size = FileOperator.size(rootDir + "/" + voiFileDir + "/" + voiFileName);
					if (size > 0) {
						try {
							content.put("file_size",((int)size/1024) + 1);
						} catch (Exception ex) {
							content.put("file_size",0);
						}
					} else {
						content.put("file_size",0);
					}
					content.put("file_dir",voiFileDir);
					content.put("file_name",voiFileName);
					content.put("content_type",this.getMmsContentType(voiFileName));
					
					//将MmsContent放进HashSet
					contents.add(content);
					par.addContent(smil.newAudio(voiFileName));
					
				}
			}
			if (par.getChildren().size() > 0) 
				smil.setPar(par);
		}
		
		//生成Smil文件
		String smilContent = smil.build();
    	String smilFileDir = rootDir + "/" + baseDir;
    	String smilFileName = file + ".smil";
    	if (FileOperator.write(smilFileDir, smilFileName, smilContent)) {
	    	Map content = new HashMap();
	    	content.put("charset",CrmConstants.Charset.UTF8);
	    	content.put("content_id",smilFileName);
	    	content.put("content_location",smilFileName);
	    	content.put("file_dir",baseDir);
	    	content.put("file_name",smilFileName);
	    	content.put("file_size",1);
	    	content.put("content_type",this.getMmsContentType(smilFileName));
	    	contents.add(content);
	    	Map mms = new HashMap();
	    	mms.put("mms_sid",UUID.randomUUID().toString());
	    	mms.put("mms_subject",subject);
	    	mms.put("corp_sid_fk",corp_sid_fk);
	    	if(!"y".equals(company) ){//个人的写入个ID
	    		mms.put("user_sid_fk",user_sid_fk);
	    	}
	    	mms.put("incoming_call_state",incomingCallState);
	    	mms.put("outcoming_call_state",outcomingCallState);
//	    	mms.put("Company(this.staff.getCompany());
	    	mms.put("create_date",new Date());
	    	mms.put("mms_size",0);
	    	
	    	for (Map content_ : contents) {
				mms.put("mms_size",(Integer)mms.get("mms_size")+(Integer)content_.get("file_size"));
				content_.put("mms_sid_fk",(String) mms.get("mms_sid"));
				Map map = mmsContentDao.getProperties(content_);
				mmsContentDao.add(map);
	    	}
	    	mmsDao.add(mms);
	    	
	    	request.setAttribute("message", this.MSG_SUCCESS);
	    	request.setAttribute("redirectUrl", this.requestUri+".do?method=list");
	    	return new ModelAndView(this.successView);
    	} else {
    		request.setAttribute("message", this.MSG_FAIL);
	    	return new ModelAndView(this.failView);
    	}
    	

    }
//	private void saveMMSendConfig(HttpServletRequest request) {
//		String defaultIncomingcallMms = StringUtils.varFormat(request.getParameter("defaultIncomingcallMms"));
//		String defaultDeelectrifyingMms = StringUtils.varFormat(request.getParameter("defaultDeelectrifyingMms"));
//		SmilFileWriter smil = new SmilFileWriter();
//		String filePath = request.getSession().getServletContext().getRealPath("/")+"fileDir/mms/";
//		int framCount = Integer.parseInt(request.getParameter("frameCount"));
//		String subject = StringUtils.varFormat(request.getParameter("subject"));
//		smil.setTitle(subject);
//		Set<MMSContentConfig> contents = new HashSet<MMSContentConfig>();
//		FileOperator fo = new FileOperator();
//		for(int i=1;i<=framCount;i++){
//			String frameTime = StringUtils.varFormat(request.getParameter("frameTime"+String.valueOf(i)));
//			Element par = smil.newPar(frameTime+"000");
//			String mmsText = StringUtils.varFormat(request.getParameter("mmsText"+String.valueOf(i)));
//			if(!"".equals(mmsText)){
////				String txtPath = fo.createTxtFile(mmsText, filePath);
////				contents.add(getContent(txtPath));
////				par.addContent(smil.newText(getFileName(txtPath)));
//			}
//			
//			String voiPath = StringUtils.varFormat(request.getParameter("voiPath"+String.valueOf(i)));
//			if(!"".equals(voiPath)){
////				contents.add(getContent(voiPath));
//				par.addContent(smil.newAudio(getFileName(voiPath)));
//			}
//			
//			String imgPath = StringUtils.varFormat(request.getParameter("imgPath"+String.valueOf(i)));
//			if(!"".equals(imgPath)){
////				contents.add(getContent(imgPath));
//				par.addContent(smil.newImg(getFileName(imgPath)));
//			}
//			smil.setPar(par);
//		}
//		String smilPath = smil.build(filePath);
////		contents.add(getContent(smilPath));
//		MMSendConfig sendConfig = new MMSendConfig();
//		//this.copyProperties(send, mms.getMMSend());
//		Company company = staff.getCompany();
//		sendConfig.setCompany(company);
//		sendConfig.setDepartment(this.staff.getDepartment());
//		sendConfig.setCorpAccount(company.getCorpAccount());
//		sendConfig.setMmsPassword(company.getMmsPassword());
//		sendConfig.setSenderAddress(company.getMmsVasId());
//		sendConfig.setServiceCode(company.getMmsServiceCode());
//		sendConfig.setVasid(company.getMmsVasId());
//		sendConfig.setVaspid(company.getMmsVaspId());
//		sendConfig.setSubject(subject);
//		if(!"".equals(defaultIncomingcallMms)){
//			sendConfig.setDefaultIncomingcallMms(MMSendConfig.DEFAULT_MMS);
//		}else{
//			sendConfig.setDefaultIncomingcallMms(MMSendConfig.NOT_DEFAULT_MMS);
//		}
//		if(!"".equals(defaultDeelectrifyingMms)){
//			sendConfig.setDefaultDeelectrifyingMms(MMSendConfig.DEFAULT_MMS);
//		}else{
//			sendConfig.setDefaultDeelectrifyingMms(MMSendConfig.NOT_DEFAULT_MMS);
//		}
//		sendConfig.setSender(this.staff.getStaffName());
//		for(MMSContentConfig content:contents){
//			content.setMmSend(sendConfig);
//		}
//		sendConfig.setContents(contents);
//		sendConfigDao.saveOrUpdate(sendConfig);
//	}
//	
	private String getMmsContentType(String fileName){
		String extName = FileOperator.getExtName(fileName);
		if (extName.toLowerCase().equals("txt")) {
			return "text/plain";
		} else if (extName.toLowerCase().equals("amr")) {
			return "audio/amr";
		} else if (extName.toLowerCase().equals("midi")) {
			return "audio/midi";
		} else if (extName.toLowerCase().equals("gif")) {
			return "image/gif";
		} else if (extName.toLowerCase().equals("jpg")) {
			return "image/jpeg";
		} else if (extName.toLowerCase().equals("jpeg")) {
			return "image/jpeg";
		} else if (extName.toLowerCase().equals("png")) {
			return "image/png";
		} else if (extName.toLowerCase().equals("smil")) {
			return "application/smil";
		} else {
			return "";
		}
	}
}